<template>
  <div class="app-main-box">
    <div class="func-btn">
      <el-button round type="default" plain icon="Back" @click="goBack">返回</el-button>
    </div>

    <div class="operate-info">
      操作人：{{ route.query.operatorName }}<span style="margin: 0 40px;">操作时间：{{ route.query.createTime }}</span>导入数量：{{
        route.query.dataAmount }}
      <el-button round type="default" plain icon="Download" @click="handleExport" class="operate-btn">导出数据</el-button>
    </div>

    <!-- 表格数据 -->
    <div class="global-table-container">
      <el-table class="global-border-radius-table" round algin="center" v-loading="loading" :data="historyData">
        <el-table-column label="磅单号" prop="weightBillNo" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="车号" prop="trainNo" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="箱号" prop="containerNo" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="篷布号" prop="coverClothNo" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="运单号" prop="waybillNo" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="货物" prop="cargo" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column label="重量(吨)" prop="weight" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column label="装车日期" prop="loadingDate" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="发站" prop="departureStation" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="到站" prop="arrivalStation" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="托运人" prop="consignor" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="收货人" prop="consignee" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="导入人" prop="creatorName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="导入时间" prop="createTime" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column fixed="right" label="操作" class-name="small-padding" min-width="240">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="openDialog(scope.row)">编辑</el-button>
            <el-button link :type="scope.row.originatingId ? 'primary' : 'info'" icon="View"
              @click="handleView(scope.row)">发端数据</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码控件 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize" @pagination="getList" :pageSizes="[15, 20, 30, 50]" />
    </div>

    <!-- 编辑铁路运单对话框 -->
    <el-dialog title="编辑运单" v-model="dialog_form_edit" width="800px" style="min-width: 750px" append-to-body>
      <!-- 编辑表单区域 -->
      <!-- 提示 -->
      <el-form-item v-if="formEdit.originatingId" class="global-tip-container" style="width: 100%;">
        <div class="global-tip">
          <span class="tip-icon"><svg-icon icon-class="light-tip" /></span>
          <div class="tip-content">
            <p>当前运单已完成发端数据匹配，无法修改箱号以及装货日期.</p>
          </div>
        </div>
      </el-form-item>
      <el-form class="global-form-edit" :model="formEdit" ref="formEditRef" :rules="formEditRules" label-width="120px">
        <el-form-item label="磅单号：" prop="weightBillNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.weightBillNo" class="form-input" placeholder="请输入磅单号"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="车号：" prop="trainNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.trainNo" class="form-input" placeholder="请输入车号" clearable></el-input>
        </el-form-item>
        <el-form-item label="箱号：" prop="containerNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.containerNo" class="form-input" placeholder="请输入箱号" clearable
            :disabled="formEdit.originatingId ? true : false"></el-input>
        </el-form-item>
        <el-form-item label="篷布号：" prop="coverClothNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.coverClothNo" class="form-input" placeholder="请输入篷布号"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="运单号：" prop="waybillNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.waybillNo" class="form-input" placeholder="请输入运单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="货物：" prop="cargo" class="form-items">
          <el-input v-noSpace v-model="formEdit.cargo" class="form-input" placeholder="请输入货物" clearable></el-input>
        </el-form-item>
        <el-form-item label="重量(吨)：" prop="weight" class="form-items">
          <el-input v-noSpace v-model="formEdit.weight" class="form-input" placeholder="请输入重量" clearable>
            <template #append>吨</template>
          </el-input>
        </el-form-item>
        <el-form-item label="装车日期：" prop="loadingDate" class="form-items">
          <el-date-picker value-format="YYYY-MM-DD" v-model="formEdit.loadingDate" type="date" placeholder="请选择装车日期"
            style="width: 100%;" clearable :disabled="formEdit.originatingId ? true : false" />
        </el-form-item>
        <el-form-item label="发站：" prop="arrivalStation" class="form-items">
          <el-input v-noSpace v-model="formEdit.arrivalStation" class="form-input" placeholder="请输入发站"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="到站：" prop="departureStation" class="form-items">
          <el-input v-noSpace v-model="formEdit.departureStation" class="form-input" placeholder="请输入到站"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="托运人：" prop="consignor" class="form-items">
          <el-input v-noSpace v-model="formEdit.consignor" class="form-input" placeholder="请输入托运人" clearable></el-input>
        </el-form-item>
        <el-form-item label="收货人：" prop="consignee" class="form-items">
          <el-input v-noSpace v-model="formEdit.consignee" class="form-input" placeholder="请输入收货人" clearable></el-input>
        </el-form-item>
      </el-form>

      <div class="dialog-footer" style="margin-top: 2px;">
        <el-button type="primary" @click="submitFormEdit">确 定</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出数据弹窗 -->
    <el-dialog title="导出数据" v-model="dialog_export" width="500px" style="min-width: 450px" append-to-body>
      <el-form-item class="global-tip-container" style="width: 100%;padding: 0 18px;">
        <div class="global-tip">
          <span class="tip-icon"><svg-icon icon-class="light-tip" /></span>
          <div class="tip-content">
            <p>本次导出数据共包含 {{ route.query.dataAmount }} 行任务...</p>
          </div>
        </div>
      </el-form-item>
      <el-form class="global-form-edit " :model="formExport" ref="formExportRef" label-width="100px">
        <el-form-item class="form-item" style="width: 100%;">
          <template #label>
            <div class="label-wrap">
              <span class="label-text">内容</span>
              <span class="label-single">：</span>
            </div>
          </template>
          <el-checkbox-group v-model="formExport.checkList">
            <el-checkbox label="0" value="0" disabled>铁路数据</el-checkbox>
            <el-checkbox label="1" value="1">发端数据</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item class="form-item" style="width: 100%;">
          <template #label>
            <div class="label-wrap">
              <span class="label-text">文件格式</span>
              <span class="label-single">：</span>
            </div>
          </template>
          <el-tag type="success" style="font-size: 14px;">xlsx</el-tag>
        </el-form-item>
      </el-form>

      <div class="dialog-footer" style="margin-top: 2px;">
        <el-button type="primary" @click="submitFormExport">确 定</el-button>
        <el-button @click="cancelExport">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 发端数据-查看运单对话框 -->
    <start-info ref="formViewRef"></start-info>
  </div>
</template>

<script setup name="transportOrderList">
import { ElMessage } from 'element-plus'
import { getListApi, getHistoryListApi, updateListApi, exportExcleApi } from "@/api/transportOrderManagement/railway";
import startInfo from '@/views/components/startInfo'
import { ref } from 'vue';
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
let dialog_export = ref(false)
let dialog_form_edit = ref(false); // 铁路运单编辑
let loading = ref(true);
let total = ref(0);
let dateRange = ref([]);
let historyData = ref([]) // 历史数据
let formViewRef = ref(null)
/** 列表查询参数 */
const data = reactive({
  formEdit: {},
  formExport: {
    checkList: ['0']
  },
  formEditRules: {
    weightBillNo: [{ required: true, message: "磅单号不能为空", trigger: "blur" }],
    trainNo: [{ required: true, message: "车号不能为空", trigger: "blur" }],
    coverClothNo: [{ required: true, message: "篷布号不能为空", trigger: "blur" }],
    waybillNo: [{ required: true, message: "运单号不能为空", trigger: "blur" }],
    cargo: [{ required: true, message: "货物不能为空", trigger: "blur" }],
    weight: [
      { required: true, message: "重量不能为空", trigger: "blur" },
      { pattern: /^(?!0(\.0+)?$)\d+(\.\d+)?$/, message: '仅允许输入大于0的小数和整数', trigger: 'blur' },
      { pattern: /^(?!0\d)(\d+(\.\d*)?|\.\d+)$/, message: '输入内容不合法', trigger: 'blur' }
    ],
    loadingDate: [{ required: true, message: "装车日期不能为空", trigger: "blur" }],
    arrivalStation: [{ required: true, message: "发站不能为空", trigger: "blur" }],
    departureStation: [{ required: true, message: "到站不能为空", trigger: "blur" }],
    consignor: [{ required: true, message: "托运人不能为空", trigger: "blur" }],
    consignee: [{ required: true, message: "收货人不能为空", trigger: "blur" }],
    containerNo: [
      { required: true, message: "箱号不能为空", trigger: "blur" },
      // { max: 11, message: "箱号不能超过11位", trigger: "blur" }
    ]
  },
  // 历史数据
  queryParams: {
    pageIndex: 1,
    pageSize: 15,
    historyImportId: '',
    waybillType: 2 // 铁路
  },
});
const { queryParams, formEdit, formExport, formEditRules } = toRefs(data);

/** 
* Methods
*/
/** 表格序号 */
// function indexMethod(index) {
//   index = index + 1
//   if (queryParamsRecord.value.pageIndex > 1) {
//     index = index + (queryParamsRecord.value.pageIndex - 1) * queryParamsRecord.value.pageSize
//   }
//   return index
// }

function goBack() {
  router.back()
}

/** 获取历史导入数据*/
function getList() {
  loading.value = true;
  queryParams.value.historyImportId = route.query.historyImportId
  let params = queryParams.value
  getListApi(proxy.addDateRange(params, dateRange.value, 'Date')).then(response => {
    if (response.code === 1) {
      historyData.value = response.data.records;
      total.value = Number(response.data.total);
      loading.value = false;
    } else {
      loading.value = false;
      // return false
    }
  }).catch(err => {
    loading.value = false;
    // return false
  })
}

/** 打开编辑对话框 */
async function openDialog(row) {
  // 打开时重置表单
  resetEditForm()
  formEdit.value = { ...row }
  dialog_form_edit.value = true;
};

/** 提交表单 */
function submitFormEdit() {
  proxy.$refs["formEditRef"].validate(valid => {
    if (valid) {
      updateList()
    }
  })
}

/** 提交编辑铁路运单列表表单 */
function updateList() {
  let row = { ...formEdit.value, railwayConsignmentId: formEdit.value.id }
  updateListApi(row).then(response => {
    if (response.code == 1) {
      updateTableRowData(response.data)
      dialog_form_edit.value = false
      ElMessage({ message: '操作成功', type: 'success' })
    } else {
      dialog_form_edit.value = false
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
    dialog_form_edit.value = false
  })
}

/** 手动更新表格中某行的数据 */
function updateTableRowData(params) {
  historyData = historyData.map(item => {
    if (item.id.toString() == params.id.toString()) {
      item = Object.assign(item, params)
    }
    return item
  });
}

/** 编辑运单对话框-取消按钮 */
function cancelEdit() {
  dialog_form_edit.value = false;
  resetEditForm();
}

/** 重置编辑运单对话框 */
function resetEditForm() {
  formEdit.value = {
    weightBillNo: undefined,
    trainNo: undefined,
    containerNo: undefined,
    coverClothNo: undefined,
    waybillNo: undefined,
    cargo: undefined,
    weight: undefined,
    loadingDate: undefined,
    arrivalStation: undefined,
    departureStation: undefined,
    consignor: undefined,
    consignee: undefined
  }
  proxy.resetForm("formEditRef");
}

/** 打开发端数据详情页面对话框 */
function handleView(row) {
  if (!row.originatingId) {
    ElMessage({ message: '未完成发端数据匹配', type: 'error' })
    return false
  }
  formViewRef.value.viewData(row)
}

/** 打开导出数据弹窗 */
function handleExport() {
  if(!historyData.value.length){
    proxy.$modal.msgError('暂无数据')
    return
  }
  // 重置导出弹窗表单
  resetExportForm()
  dialog_export.value = true
}

/** 重置导出数据表单 */
function resetExportForm() {
  formExport.value = {
    checkList: ['0']
  }
}

/** 提交导出数据 */
function submitFormExport() {
  exportExcle()
}


/** 下载对账单API */
async function exportExcle() {
  let isClude = false
  let filename = ''
  if (formExport.value.checkList.length > 1) {
    filename = `铁路发端汇总_${getCurrentFormattedTime()}` + '.xlsx'
    isClude = true
  } else {
    filename = `铁路数据_${getCurrentFormattedTime()}` + '.xlsx'
  }
  let params = { importId: route.query.historyImportId, includeOriginatingData: isClude }
  exportExcleApi(params).then((response) => {
    // const disposition = response.headers['content-disposition'];
    // const matchArray = disposition.match(/filename="(.*)"/);
    // const filename = matchArray[1];
    const url = window.URL.createObjectURL(response);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click()
    document.body.removeChild(link); // 下载完成后移除元素
    window.URL.revokeObjectURL(url); // 释放URL对象
    dialog_export.value = false
  }).catch(() => {
  })
}


/** 生成文件名 */
function getCurrentFormattedTime() {
  const now = new Date();
  // 获取年、月、日、时、分、秒
  const year = now.getFullYear();
  // getMonth() 返回 0-11，所以需要加1
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');

  // 构建格式化的字符串
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

/** 取消导出数据 */
function cancelExport() {
  dialog_export.value = false
}

getList()
</script>

<style lang='scss' scoped>
@import '../../../assets/styles/variables.module.scss';

.app-main-box {
  background: #fff;
  border-radius: 12px;
  min-height: calc(100vh - 125px);
  width: calc(100% - 40px);

  .global-tip-container {
    display: flex;
    align-items: flex-start !important
  }

  /** 功能按钮 */
  .func-btn {
    padding: 24px 24px 0px;
  }

  .operate-info {
    text-align: center;
    font-size: 12px;
    color: $--color-info;
    height: 50px;
    line-height: 50px;
    margin: 0 24px;
    position: relative;

    .operate-btn {
      position: absolute;
      right: 0;
      top: 0;
    }
  }

  // .global-table-container {
  //   padding: 0px 24px;
  // }

  /** el-select下拉气泡框样式 */
  // .search-select-option {
  //   :deep(.el-popper) {
  //     background-color: #fff;
  //     border: none !important;
  //     box-shadow: none !important;
  //   }

  //   :deep(.el-popper__arrow) {
  //     position: absolute;
  //     left: 0;
  //     z-index: 2000;
  //     transform: translate(calc(50% - 105px), 8px) rotate(90deg);
  //   }

  //   :deep(.el-select-dropdown) {
  //     width: 210px !important;
  //     position: absolute;
  //     top: 14px;
  //     right: 10px !important; // 根据form-item padding决定，原本padding20px，后来又改成了10px
  //     background: #fff;
  //     box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  //     overflow: hidden;
  //   }
  // }
}

/** 导入说明文本 */
// :deep(.el-upload__text) {
//   width: 100%;
// }

// :deep(.el-upload-instructment) {
//   width: 100%;
//   display: flex;
//   flex-direction: column;
//   justify-content: center;
//   align-items: center;

//   .file-info {
//     display: flex;
//     align-items: center;
//     justify-content: center;
//     flex-wrap: nowrap;
//     width: 24em;

//     .file-name {
//       font-size: 18px;
//       display: inline-block;
//       flex: 0 1 auto;
//       overflow: hidden;
//       text-overflow: ellipsis;
//       white-space: nowrap;
//     }

//     .file-size {
//       font-size: 14px;
//       align-self: flex-end;
//       color: $--color-info;
//       display: inline-block;
//       flex: 0 1 auto;
//     }
//   }

//   .instructment-text {
//     font-size: 18px;
//     color: #333;
//     font-weight: bold;
//   }

//   .suppose-type-text {
//     display: inline-block;
//     font-size: 12px;
//     color: $--color-info;
//     margin-top: 10px;
//   }

//   .download-template {
//     span {
//       font-size: 14px;
//       color: $--color-primary;
//       display: inline-block !important;
//       padding: 10px;
//     }
//   }
// }

// :deep(.el-upload-dragger) {
//   width: 100%;
//   padding: 0px !important;
//   display: flex;
//   justify-content: center;
//   align-items: center;
//   background-color: transparent !important;
//   border: none !important;
//   border-radius: 0px !important;
// }

// :deep(.el-icon--upload) {
//   margin-bottom: 0px !important;
// }

/** 上传区域样式 */
// .upload-content {
//   border: 1px dashed $--color-info;
//   background-color: $--color-bg-info !important;
//   box-sizing: border-box !important;
//   width: 100%;
//   min-height: 400px;
//   display: flex;
//   flex-direction: column;
//   align-items: center;
//   justify-content: center;
//   border-radius: 6px !important;
// }

/** 上传失败区域 */
// .upload-fail-content {
//   width: 100%;
//   height: 100%;
//   display: flex;
//   flex-direction: column;
//   align-items: center;

//   .upload-fail-line {
//     display: flex;
//     align-items: center;

//     .upload-fail-text {
//       font-size: 20px;
//       color: #333;
//       font-weight: bold;
//       margin-left: 14px;
//     }
//   }

//   .upload-fail-instructment {
//     color: $--color-info;
//     margin-top: 14px;
//   }

//   .upload-fail-table {
//     width: 100%;
//     height: 240px;
//     margin-top: 20px;

//     .infinite-list-wrapper {
//       width: 100%;
//       height: 100%;
//       border-radius: 6px;
//       background-color: $--color-bg-info;
//       padding: 0px 20px;
//       overflow-y: auto;
//     }

//     .list {
//       padding: 0;
//       margin: 0;
//       list-style: none;

//       .list-item {
//         display: flex;
//         align-items: flex-end;
//         height: 30px;
//         line-height: 1;
//         color: $--color-danger;
//         white-space: nowrap;
//       }
//     }

//   }
// }

/** 隐藏上传的文本列表 */
// :deep(.el-upload-list) {
//   display: none;
// }

/** 重新选择按钮 */
// .toggle-btn {
//   display: inline-block;
//   margin-top: 14px;
// }

/** 文件图标 */
// .file-icon {
//   width: 50px;
//   height: 50px;
//   color: #fff;
//   font-size: 30px;
//   font-style: italic;
//   font-weight: bold;
//   background-color: #00b42a; // 与字体主题色success一致
//   border-radius: 4px;
//   text-align: center;
//   line-height: 50px;
//   margin-bottom: 14px;

// }

// .upload-success-text {
//   margin-top: 20px;
// }

.label-wrap {
  display: flex;
  flex-wrap: nowrap;

  .label-text {
    height: 36px;
    text-align: justify;
    display: inline-block;
    width: 4em;
    color: #515a6e;
    font-weight: bold;

    &::after {
      display: inline-block;
      content: "-";
      width: 4em;
      opacity: 0;
    }
  }

  .label-single {
    width: max-content;
  }
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}
</style>